package models

import (
	"gin-blog/config"
	"time"

	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
)

type User struct {
	ID        uint      `json:"id" gorm:"primary_key"`
	Username  string    `json:"username" gorm:"unique;not null"`
	Email     string    `json:"email" gorm:"unique;not null"`
	Password  string    `json:"-" gorm:"not null"`
	Role      string    `json:"role" gorm:"default:'user'"`
	Avatar    string    `json:"avatar"`
	Bio       string    `json:"bio"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	// Posts     []Post    `json:"posts,omitempty" gorm:"foreignkey:AuthorID"`
}

// 创建用户前加密密码
func (u *User) BeforeCreate(scope *gorm.Scope) error {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	scope.SetColumn("Password", string(hashedPassword))
	return nil
}

// 验证密码
func (u *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	return err == nil
}

// 创建默认管理员用户
func CreateDefaultAdmin() {
	var count int
	config.DB.Model(&User{}).Count(&count)

	if count == 0 {
		admin := User{
			Username: "admin",
			Email:    "admin@example.com",
			Password: "admin123",
			Role:     "admin",
			Bio:      "系统管理员",
		}
		config.DB.Create(&admin)
	}
}
